package com.mftour.moudles.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.mftour.common.Constant;
import com.mftour.common.utils.JsonUtil;
import com.mftour.common.utils.StringUtil;
import com.mftour.moudles.entity.Role;
import com.mftour.moudles.entity.RolePermission;
import com.mftour.moudles.entity.User;
import com.mftour.moudles.service.ConsolePermissionService;
import com.mftour.moudles.service.RolePermissionService;
import com.mftour.moudles.service.RoleService;
import com.mftour.moudles.service.RoleUserService;
import com.mftour.moudles.service.UserService;
import com.mftour.moudles.vo.AjaxResponse;
import com.mftour.moudles.vo.RoleSearchPagingVo;
import com.mftour.moudles.vo.SelectRoleVo;
import com.mftour.moudles.vo.SelectUserVo;
import com.mftour.moudles.vo.ShowPage;

@Controller
@RequestMapping(value = "/role")
public class RoleController extends BaseController {

	@Autowired
	private RoleService roleSer;

	@Autowired
	private RolePermissionService rolePermissionSer;

	@Autowired
	private UserService userSer;

	@Autowired
	private RoleUserService roleUserSer;

	@Autowired
	private ConsolePermissionService consolePermissionSer;

	@RequestMapping(value = "/list")
	public ModelAndView toRoleList(RoleSearchPagingVo roleSearchPagingVo) {
		ModelAndView mv = new ModelAndView("system/roleList");
		List<Role> roleList = roleSer.selectRoleListSelectivePaging(roleSearchPagingVo);
		ShowPage page = null;
		page = new ShowPage(roleSearchPagingVo, roleList);
		mv.addObject("page", page);
		mv.addObject("roleSearchPagingVo", roleSearchPagingVo);
		return mv;
	}

	@RequestMapping(value = "/ajax/save", method = RequestMethod.POST)
	@ResponseBody
	public String save(Role role) {
		role.setRoleId(null);
		role.setCreatedUser(loginUser.getUserId().toString());
		role.setUpdatedUser(loginUser.getUserId().toString());
		roleSer.insertSelective(role);
		if (role.getRoleId() == null) {
			AjaxResponse ajaxResponse = new AjaxResponse(Constant.RS_CODE_ERROR, "添加角色出错！");
			return JsonUtil.writeValueAsString(ajaxResponse);
		}

		AjaxResponse ajaxResponse = new AjaxResponse(Constant.RS_CODE_SUCCESS, "添加角色成功！");
		return JsonUtil.writeValueAsString(ajaxResponse);
	}

	@RequestMapping(value = "/ajax/del", method = RequestMethod.POST)
	@ResponseBody
	public String del(Integer roleId) {
		roleSer.deleteByPrimaryKey(roleId);
		AjaxResponse ajaxResponse = new AjaxResponse(Constant.RS_CODE_SUCCESS, "删除角色成功！");
		return JsonUtil.writeValueAsString(ajaxResponse);
	}

	@RequestMapping(value = "/ajax/delAll", method = RequestMethod.POST)
	@ResponseBody
	public String delAll(Integer[] roleIds) {
		AjaxResponse ajaxResponse = new AjaxResponse(Constant.RS_CODE_ERROR, "请选择删除项！");
		if (roleIds == null || roleIds.length < 1) {
			return JsonUtil.writeValueAsString(ajaxResponse);
		}

		roleSer.deleteByPKs(roleIds);
		ajaxResponse.setCode(Constant.RS_CODE_SUCCESS);
		ajaxResponse.setMsg("批量删除角色成功!");
		return JsonUtil.writeValueAsString(ajaxResponse);
	}

	@RequestMapping(value = "/ajax/update", method = RequestMethod.POST)
	@ResponseBody
	public String update(Role role) {
		role.setUpdatedAt(new Date());
		role.setUpdatedUser(loginUser.getUserId().toString());
		roleSer.updateByPrimaryKeySelective(role);
		AjaxResponse ajaxResponse = new AjaxResponse(Constant.RS_CODE_SUCCESS, "修改角色成功！");
		return JsonUtil.writeValueAsString(ajaxResponse);
	}

	@RequestMapping(value = "/ajax/entity", method = RequestMethod.GET)
	@ResponseBody
	public String getEntity(Integer roleId) {
		Role role = roleSer.selectByPrimaryKey(roleId);
		AjaxResponse ajaxResponse = new AjaxResponse(Constant.RS_CODE_SUCCESS, "获取角色成功！");
		if (role != null) {
			ajaxResponse.setData(role);
		} else {
			ajaxResponse.setCode(Constant.RS_CODE_ERROR);
			ajaxResponse.setMsg("获取角色失败！");
		}
		return JsonUtil.writeValueAsString(ajaxResponse);
	}

	@RequestMapping(value = "/ajax/toConfigPermisson")
	public ModelAndView toConfigPermisson(String roleId) {
		RolePermission rp = new RolePermission();
		rp.setRoleId(Integer.parseInt(roleId));
		Set<Integer> rpSet = new HashSet<Integer>();
		List<RolePermission> rps = rolePermissionSer.selectListSelective(rp);
		for (RolePermission rolePermission : rps) {
			rpSet.add(rolePermission.getPermissionId());
		}

		ModelAndView mv = new ModelAndView("system/configPermission");
		mv.addObject("rpSet", rpSet);
		mv.addObject("roleId", roleId);
		return mv;
	}

	@RequestMapping(value = "/ajax/saveRolePermissions", method = RequestMethod.POST)
	@ResponseBody
	public String saveRolePermissions(String permissionIds, Integer roleId) {
		AjaxResponse ajaxResponse = new AjaxResponse(Constant.RS_CODE_SUCCESS, "分配角色权限成功！");
		if (!rolePermissionSer.updateRolePermissions(permissionIds, roleId)) {
			ajaxResponse.setCode(Constant.RS_CODE_ERROR);
			ajaxResponse.setMsg("分配角色权限失败！");
		} else {
			consolePermissionSer.refreshAllUserMenuPermissions();
		}
		return JsonUtil.writeValueAsString(ajaxResponse);
	}

	@RequestMapping(value = "/ajax/users", method = RequestMethod.GET)
	@ResponseBody
	public String getUsersByRoleId(Integer roleId) {
		AjaxResponse ajaxResponse = new AjaxResponse(Constant.RS_CODE_SUCCESS, "获取角色拥有用户成功！");
		List<User> selectedUsers = userSer.getUsersByRoleId(roleId);
		User record = new User();
		record.setUserStatus(Constant.STATUS_NORMAL);
		List<User> allUsers = userSer.selectListSelective(record);
		List<SelectUserVo> result = new ArrayList<SelectUserVo>();
		for (User user : allUsers) {
			SelectUserVo uVo = new SelectUserVo();
			uVo.setLoginId(user.getLoginId());
			uVo.setUserId(user.getUserId());
			uVo.setUserName(user.getUserName());

			if (selectedUsers != null && selectedUsers.contains(user)) {
				uVo.setSelected(true);
			}
			result.add(uVo);
		}
		ajaxResponse.setData(result);
		return JsonUtil.writeValueAsString(ajaxResponse);
	}

	@RequestMapping(value = "/ajax/saveRoleUsers", method = RequestMethod.POST)
	@ResponseBody
	public String saveRoleUsers(String selectedUsers, Integer selectRoleId) {
		AjaxResponse ajaxResponse = new AjaxResponse(Constant.RS_CODE_SUCCESS, "分配用户成功！");
		roleUserSer.updateRoleUsers(selectedUsers, selectRoleId);
		consolePermissionSer.refreshAllUserMenuPermissions();
		return JsonUtil.writeValueAsString(ajaxResponse);
	}

	@RequestMapping(value = "/ajax/roles", method = RequestMethod.GET)
	@ResponseBody
	public String getRolesByUserId(Integer userId) {
		AjaxResponse ajaxResponse = new AjaxResponse(Constant.RS_CODE_SUCCESS, "获取用户拥有角色成功！");
		List<Role> selectedRoles = roleSer.selectRolesByUserId(userId);
		List<Role> allRoles = roleSer.selectListSelective(null);
		List<SelectRoleVo> result = new ArrayList<SelectRoleVo>();
		for (Role role : allRoles) {
			SelectRoleVo rVo = new SelectRoleVo();
			rVo.setRoleCode(role.getRoleCode());
			rVo.setRoleId(role.getRoleId());
			rVo.setRoleName(role.getRoleName());

			if (selectedRoles != null && selectedRoles.contains(role)) {
				rVo.setSelected(true);
			}
			result.add(rVo);
		}
		ajaxResponse.setData(result);
		return JsonUtil.writeValueAsString(ajaxResponse);
	}

	@RequestMapping(value = "/ajax/saveUserRoles", method = RequestMethod.POST)
	@ResponseBody
	public String saveUserRoles(String selectedRoles, Integer selectUserId) {
		AjaxResponse ajaxResponse = new AjaxResponse(Constant.RS_CODE_SUCCESS, "给用户分配角色成功！");
		roleUserSer.updateUserRoles(selectedRoles, selectUserId);
		consolePermissionSer.refreshAllUserMenuPermissions();
		return JsonUtil.writeValueAsString(ajaxResponse);
	}
}
